package love.bot.forli.group.review.interceptor;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import love.bot.forli.group.review.bean.Result;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.WebUtils;

/**
 * @author 无以铭川
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    public static final String SALT = "salt";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getRequestURI());
        String auth = request.getHeader("Authorization");
        if (auth == null) {
            Result<Object> res = new Result<>();
            res.setCode(401);
            res.setMsg("认证失败");
            out(response, res);
            return false;
        }
        JSONObject jsonObject = JSONObject.parseObject(auth);
        String username = jsonObject.getString("username");
        String hash = jsonObject.getString("hash");
        if (username != null && hash != null) {
            String encode = MD5Encoder.encode(MessageDigest.getInstance("MD5").digest((username + SALT).getBytes(StandardCharsets.UTF_8)));
            if (encode.equals(hash)) {
                return true;
            }
        }
        Result<Object> res = new Result<>();
        res.setCode(401);
        res.setMsg("认证失效");
        out(response, res);
        return false;
    }

    /**
     * json形式返回结果token验证失败信息，无需转发
     */
    private void out(ServletResponse response, Result<Object> res) throws IOException {
        HttpServletResponse httpServletResponse = WebUtils.getNativeResponse(response, HttpServletResponse.class);
        ObjectMapper mapper = new ObjectMapper();
        String jsonRes = mapper.writeValueAsString(res);
        assert httpServletResponse != null;
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        httpServletResponse.getOutputStream().write(jsonRes.getBytes());
    }
}
